package com.example.demo.configuration.inter;

import com.example.demo.SpringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;

@Component
public class CustomStringSerializer
        extends StdScalarSerializer<String>
{
    private static final long serialVersionUID = 1L;


    public CustomStringSerializer() { super(String.class, false); }

    @Override
    public boolean isEmpty(SerializerProvider prov, String value) {
        String str = value;
        return str.length() == 0;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        Object objValue = gen.getCurrentValue();
        String fieldName = gen.getOutputContext().getCurrentName();
        ShowRuleHandler showRuleHandler = SpringUtils.getBean(ShowRuleHandler.class);
        String typCode = showRuleHandler.getTypeCodeValue(objValue);
        //无意义指标处理
        String invalidValue = showRuleHandler.getInvalidValue(typCode, fieldName);
        if(invalidValue != null){
            gen.writeString(invalidValue);
        }else{
            gen.writeString(value);
        }
    }

    @Override
    public final void serializeWithType(String value, JsonGenerator gen, SerializerProvider provider,
                                        TypeSerializer typeSer) throws IOException
    {
        // no type info, just regular serialization
        gen.writeString(value);
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
        ShowRuleHandler showRuleHandler = SpringUtils.getBean(ShowRuleHandler.class);
        if(showRuleHandler.isEnable()) {
            CustomNullSerializer customNullSerializer = SpringUtils.getBean(CustomNullSerializer.class);
            provider.setNullValueSerializer(customNullSerializer);
        }
        return createSchemaNode("string", true);
    }

    @Override
    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        visitStringFormat(visitor, typeHint);
    }
}
